#include<workflow/Workflow.h>
#include<workflow/WFFacilities.h>
#include<workflow/WFTaskFactory.h>
#include<iostream>
#include<string>
#include<signal.h>

using std::cerr;
using std::cout;
using std::string;

static WFFacilities::WaitGroup  waitgroup(1); 

struct SeriesContext 
{
    string html;
};

void handler(int signalnum)
{
    waitgroup.done();
    cout<<"done\n";
}

void httpcallback(WFHttpTask* httptask)
{
	protocol::HttpResponse *resp = httptask->get_resp();
	int state = httptask->get_state();
	int error = httptask->get_error();
    const void *body;
    // val用来保存redis执行的结果
	protocol::RedisValue val;
    switch (state){
	case WFT_STATE_SYS_ERROR:
		std::cout <<"system error: " << strerror(error) << "\n";
		break;
	case WFT_STATE_DNS_ERROR:
		cerr <<"DNS error: "  << gai_strerror(error) << "\n";
		break;
	case WFT_STATE_SSL_ERROR:
		cerr <<"SSL error\n";
		break;
	case WFT_STATE_TASK_ERROR:
		cerr <<"Task error\n";
		break;
	case WFT_STATE_SUCCESS:
    {
	size_t body_len;
	resp->get_parsed_body(&body, &body_len);
    SeriesContext * context = static_cast<SeriesContext *>(series_of(httptask)->get_context());
    context->html=(char*)body;
    }
		break;
	}

	//创建任务
	WFRedisTask * redisTask2 = WFTaskFactory::create_redis_task("redis://127.0.0.1:6379",10,[](WFRedisTask* rh){cout<<"finsih\n";});
	SeriesWork * series = series_of(httptask); //找到当前任务所在的序列
    SeriesContext* pt=static_cast<SeriesContext*> (series->get_context());
	redisTask2->get_req()->set_request("set",{"62test",pt->html.c_str()}); //设置任务的指令
	// //把任务交给框架调度运行
	// redisTask2->start();
	series->push_back(redisTask2); //该序列正在运行中，只能往末尾添加任务
}

int main()
{
    signal(SIGINT,handler);
    WFHttpTask * httptask = WFTaskFactory::create_http_task("http://www.taobao.com",10,10,httpcallback);
    SeriesWork * serise = Workflow::create_series_work(httptask,[](const SeriesWork* se){
        std::cout<<" done \n";
    });
    SeriesContext* context= new SeriesContext;
    serise->set_context(context);
    serise->start();
    waitgroup.wait();
}